from google.appengine.api import users


from django.shortcuts import render_to_response

from helpers.choices import OBJ_HANDLER
from people.models import Invite

def invite_add(request, key):
	if not request.method == 'POST':
		return render_to_response('people/invite/add.html')
	user = users.User(request.POST.get('user'))
	if not user:
		return render_to_response('people/invite/error.html')

	entry_k = request.POST.get('entry_k')
	mask = int(request.POST.get('mask'))
	
	try:
		entry = OBJ_HANDLER[entry_k].all().filter('s_key =', key)[0]
	except:
		return render_to_response('people/invite/error.html')
	
	if not entry.is_owner():
		return render_to_response('people/invite/error.html')

	invite = Invite(permission = mask, user = user, entry = entry)
	if invite.save():
		return render_to_response('people/invite/add.html')
	return render_to_response('people/invite/error.html')

def invite_edit(request, key):
	if not request.method == 'POST':
		return render_to_response('people/invite/add.html')
	invite = Invite.all().filter('s_key =', key)[0]

	if not invite.is_owner():
		return render_to_response('people/invite/error.html')
		
	user = users.User(request.POST.get('user'))
	if not user:
		return render_to_response('people/invite/error.html')

	entry_k = request.POST.get('entry_k')
	entry_skey = request.POST.get('s_key')
	mask = request.POST.get('mask')
	
	try:
		entry = OBJ_HANDLER[entry_k].all().filter('s_key =', entry_skey)[0]
	except:
		return render_to_response('people/invite/error.html')
	
	if entry != invite.entry or entry.author != user:
		return render_to_response('people/invite/error.html')

	invite.mask = mask

	if invite.save():
		return render_to_response('people/invite/add.html')
	return render_to_response('people/invite/error.html')

def invite_remove(request, key):
	if not request.method == 'POST':
		return render_to_response('people/invite/add.html')
	author = users.get_current_user()
	invite = Invite.all().filter('s_key =', key)[0]

	if invite.entry.author != author or invite.author != author:
		return render_to_response('people/invite/error.html')
		
	if db.delete(invite):
		return render_to_response('people/invite/add.html')
	return render_to_response('people/invite/error.html')
